<template>
  <div class="app-container">
    <div class="row">
      <div class="col">
        <el-card class="box-card">
          <el-form :inline="true">
            <!-- <el-form-item label="角色">
              <el-select v-model="roleId" placeholder="请选择角色" clearable="">
                <el-option
                  v-for="item in roleList"
                  :key="item.roleId"
                  :value="item.roleId"
                  :label="item.name"
                />
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item>
              <el-button type="primary" @click="clickHandle">授权</el-button>
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" @click="initPermissionCache">
                初始化缓存
              </el-button>
            </el-form-item>
          </el-form>

          <el-table :data="roleList" border fit stripe :height="tableHeight">
            <el-table-column prop="name" label="角色名称" />
            <el-table-column
              fixed="right"
              align="center"
              header-align="center"
              label="操作"
              width="100"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="clickHandle(scope.row)"
                >
                  授权
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
      <div class="col-flex" v-if="dialogFormVisible">
        <el-card class="box-card" v-loading="getTreeLoading">
          <div slot="header" class="clearfix" style="line-height: 31px">
            <el-switch
              v-model="checkStrictly"
              align="right"
              active-text="级联勾选"
              :active-value="false"
              :inactive-value="true"
              @change="checkStrictlyChange"
            />
            <b style="font-size: 18px; float: right">{{ roleName }}</b>
          </div>
          <el-tree
            class="menu-tree"
            ref="tree"
            :data="treeData"
            :props="defaultProps"
            :check-strictly="checkStrictly"
            show-checkbox
            node-key="id"
            :style="{
              height: tableHeight - 52 + 'px',
              overflowY: 'scroll'
            }"
          />
          <div style="padding-top: 10px;">
            <el-button type="primary" @click="updateData" :loading="btnLoading">
              提交
            </el-button>
            <el-button @click="dialogFormVisible = false">取消</el-button>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import permissionAPI from './api/permissionAPI'

export default {
  name: 'SysPermission',
  data () {
    return {
      domainList: [
        {
          value: '1',
          label: '一码游标准版'
        }
      ],
      domainId: import.meta.env.VITE_APP_domainId,
      roleList: [],
      roleId: undefined,
      roleName: '',
      dialogFormVisible: false,
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      treeData: [],
      btnLoading: false,
      getTreeLoading: false,
      tableHeight: 600
    }
  },
  created () {
    this.getRoleList()
    this.tableHeight = window.innerHeight - 235
  },
  methods: {
    getRoleList () {
      permissionAPI.roleForForceAuthorize().then(response => {
        this.roleList = response.data
        if (this.roleList && this.roleList.length > 0) {
          this.roleId = this.roleList[0].roleId
        }
      })
    },
    checkStrictlyChange (value) {
      this.checkStrictly = value
    },
    clickHandle (row) {
      this.roleId = row.roleId
      this.roleName = row.name
      // if (!this.roleId || this.roleId.trim() === '') {
      //   this.$swal.error('请选择角色')
      //   return false
      // }
      this.dialogFormVisible = true
      this.resourceForAuthorize(this.roleId)
    },
    domainSelectChange () {
      this.resourceForAuthorize(this.roleId)
    },
    resourceForAuthorize (roleId) {
      this.getTreeLoading = true
      permissionAPI
        .resourceForAuthorize({ roleId: roleId, buttonAsLeaf: 1 })
        .then(response => {
          this.treeData = response.data
          const checkedKeys = []
          const remap = function (checkedArr, arr) {
            for (let i = 0; i < arr.length; i++) {
              if (arr[i].hasPermission && arr[i].hasPermission === 1) {
                checkedArr.push(arr[i].id)
              }
              if (arr[i].children) {
                remap(checkedArr, arr[i].children)
              }
            }
          }
          remap(checkedKeys, this.treeData)
          this.checkStrictly = true
          this.$nextTick(() => {
            if (this.$refs.tree) {
              this.$refs.tree.setCheckedKeys(checkedKeys)
            }
            this.checkStrictly = false
            this.$forceUpdate()
          })
        })
        .finally(_ => {
          this.getTreeLoading = false
        })
    },
    updateData () {
      const tree = this.$refs.tree
      const checkedKeys = tree
        .getCheckedKeys()
        .concat(tree.getHalfCheckedKeys())
      const postData = Object.assign(
        {},
        {
          // domainId: this.domainId,
          roleId: this.roleId,
          resourceIds: checkedKeys
        }
      )
      this.btnLoading = true
      permissionAPI
        .forceAuthorize(postData)
        .then(res => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '授权成功',
            type: 'success',
            duration: 2000
          })
        })
        .finally(_ => {
          this.btnLoading = false
        })
    },
    initPermissionCache () {
      const roleId = this.roleId
      permissionAPI.initPermissionCache({ roleId: roleId }).then(response => {
        this.$notify({
          title: '成功',
          message: '初始化成功',
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
:deep(.box-card) {
  .menu-tree {
    .el-tree-node__content {
      height: auto;
      .el-tree-node__expand-icon {
        font-size: 16px;
      }
      .is-leaf {
        font-size: 0;
      }
      .el-tree-node__label {
        font-size: 14px;
        line-height: 40px;
        border-bottom: 1px solid #ebeef5;
        flex: 1;
      }
    }
  }
}
.row {
  display: flex;
  .col {
    width: 400px;
    margin-right: 10px;
  }
  .col-flex {
    flex: 1;
  }
}
</style>
